package com.eurasia.assignment.controller;

import com.eurasia.assignment.domain.ProjectAssignment;
import com.eurasia.assignment.service.port.out.ProjectAssignmentPort;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.eurasia.assignment.controller.dto.CreateProjectRequest;
import com.eurasia.assignment.controller.dto.PageResponse;
import com.eurasia.assignment.controller.dto.ProjectResponse;
import com.eurasia.assignment.controller.dto.ProjectSearchRequest;
import com.eurasia.assignment.domain.Project;
import com.eurasia.assignment.service.FileService;
import com.eurasia.assignment.service.ProjectService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 项目控制器
 */
@RestController
@RequestMapping("/projects")
@Slf4j
@RequiredArgsConstructor
public class ProjectController {

    private final ProjectService projectService;
    private final FileService fileService;
    private final ProjectAssignmentPort getProjectAssignmentPort;

    /**
     * 查询项目列表（支持分页和条件查询）
     * @param name 项目名称（模糊查询）
     * @param type 项目类型（精确查询）
     * @param status 项目状态（精确查询）
     * @param page 页码（从0开始）
     * @param size 每页大小
     * @param sortBy 排序字段
     * @param sortDirection 排序方向（asc/desc）
     * @return 项目分页列表
     */
    @GetMapping("")
    public ResponseEntity<PageResponse<ProjectResponse>> searchProjects(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String status,
            @RequestParam(required = false, defaultValue = "0") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false, defaultValue = "asc") String sortDirection) {
        
        // 记录接收到的参数
        log.debug("接收到查询请求: name={}, type={}, status={}, page={}, size={}, sortBy={}, sortDirection={}",
                name, type, status, page, size, sortBy, sortDirection);
        
        // 构建查询请求
        ProjectSearchRequest searchRequest = new ProjectSearchRequest();
        searchRequest.setName(name);
        searchRequest.setType(type);
        searchRequest.setStatus(status);
        searchRequest.setPage(page);
        searchRequest.setSize(size);
        searchRequest.setSortBy(sortBy);
        searchRequest.setSortDirection(sortDirection);
        
        // 执行分页查询
        Page<Project> projectPage = projectService.searchProjectsWithPagination(searchRequest);
        
        // 使用 map 转换域对象到响应对象
        Page<ProjectResponse> responsePage = projectPage.map(project -> ProjectResponse.fromDomain(project, null));
        
        log.debug("查询结果: 总条数={}, 总页数={}, 当前页记录数={}",
                responsePage.getTotalElements(),
                responsePage.getTotalPages(),
                responsePage.getNumberOfElements());
        
        // 构建分页响应
        return ResponseEntity.ok(PageResponse.from(responsePage));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ProjectResponse> getProjectById(@PathVariable Long id) {
        try {
            Project project = projectService.getProjectById(id);
            ProjectAssignment projectAssignment = getProjectAssignmentPort.getAssignmentByProjectId(id);
            return ResponseEntity.ok(ProjectResponse.fromDomain(project, projectAssignment));
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 创建项目
     */
    @PostMapping(value = "", consumes = "multipart/form-data")
    public ResponseEntity<ProjectResponse> createProject(
            @RequestParam("name") String name,
            @RequestParam("type") String type,
            @RequestParam("course") String course,
            @RequestParam("points") Integer points,
            @RequestParam(value = "creator", required = false) String creator,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "finishTime", required = false) String finishTime,
            @RequestParam(value = "comment", required = false) String comment,
            @RequestParam(value = "file", required = false) MultipartFile file) {
        
        CreateProjectRequest request = new CreateProjectRequest();
        request.setName(name);
        request.setType(type);
        request.setCourse(course);
        request.setPoints(points);
        request.setCreator(creator);
        request.setStartTime(startTime);
        request.setFinishTime(finishTime);
        request.setComment(comment);
        
        // 使用专门的带文件上传的方法创建项目
        Project createdProject = projectService.createProjectWithFile(request, file);
        return ResponseEntity.ok(ProjectResponse.fromDomain(createdProject, null));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ProjectResponse> updateProject(@PathVariable Long id, @RequestBody Project projectDetails) {
        try {
            Project updatedProject = projectService.updateProject(id, projectDetails);
            return ResponseEntity.ok(ProjectResponse.fromDomain(updatedProject, null));
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProject(@PathVariable Long id) {
        try {
            projectService.deleteProject(id);
            return ResponseEntity.noContent().build();
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }
} 